package com.zztl.infiniteBand.net


import com.zztl.infiniteBand.BuildConfig
import com.zztl.infiniteBand.net.converter.EncodeConverterFactory
import com.zztl.infiniteBand.net.imp.Api
import com.zztl.infiniteBand.net.imp.DownLoadListener
import com.zztl.infiniteBand.storage.BillPreference
import com.zztl.infiniteBand.storage.PreferenceKeys
import com.zztl.infiniteBand.util.UiUtils
import com.zztl.infiniteBand.util.language.SPUtil
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import okhttp3.RequestBody
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.io.File
import java.util.concurrent.TimeUnit


/**
 * @desc
 * @auth ${user}
 * @time 2018/3/14  16:49
 */

class RetorfitServiceManger private constructor() {

    private val mRetrofit: Retrofit

    val apiService: Api

    init {

        val builder = OkHttpClient.Builder().apply {
            connectTimeout(DEFAULT_TIME_OUT.toLong(), TimeUnit.SECONDS)
            writeTimeout(DEFAULT_TIME_OUT.toLong(), TimeUnit.SECONDS)
            readTimeout(DEFAULT_TIME_OUT.toLong(), TimeUnit.SECONDS)
        }

        (BillPreference.getApp(PreferenceKeys.TOKEN.name, "") as String).run {
            HttpCommonInterceptor.Builder()
//                    .addHeaderParams("authorization", this)
//                    .addHeaderParams("Accept-Language",if(SPUtil.getInstance(UiUtils.context)?.selectLanguage==0) "en-US" else "zh-CN")
                    .build().let {
                        builder.addInterceptor(it)
                    }
        }

        mLoadListener?.apply {
            builder.addInterceptor(DownLoadInterceptor(this))
        }

        mRetrofit = Retrofit.Builder()
                .client(builder.build())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(EncodeConverterFactory.create())
                .baseUrl(BuildConfig.BASURL)
                .build()
        apiService = mRetrofit.create(Api::class.java)
    }


    companion object {
        private val BASE_URL = "http://app.hqhhh.net/app/"//正式服务器
        //                        private val BASE_URL = "http://172.16.20.134:8085/app/"//傅服务器
//            private val BASE_URL = "http://172.16.20.125:8090/app/"//冯服务器
//        private const val BASE_URL = "http://zztl1.f3322.net:8888/app/"//测试服务器
        //        public static  String BASE_IMG_URL="https://xcb.bf258.com:4443";

        val BASE_IMG_URL =  BuildConfig.BASURL.substring(0,  BuildConfig.BASURL.length - 5)
        private const val DEFAULT_TIME_OUT = 30//超时时间 30s
        private var mLoadListener: DownLoadListener? = null

        var instance: RetorfitServiceManger? = null
            get() {
                return field ?: kotlin.run {
                    field = RetorfitServiceManger()
                    return field
                }
            }


        fun reSetRetroServiceManager() {
            instance = null

        }

        fun setLoadListener(loadListener: DownLoadListener){
            this.mLoadListener=loadListener
        }


        fun <T> observe(observable: Observable<T>): Observable<T> {
            return observable.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .unsubscribeOn(Schedulers.io())
        }

        fun parseRequestBody(value: String): RequestBody {
            return RequestBody.create(MediaType.parse("text/plain"), value)
        }

        fun parseImageRequestBody(key: String, file: File): MultipartBody.Part {
            val requestBody = RequestBody.create(MediaType.parse("image/*"), file)
            return MultipartBody.Part.createFormData(key, file.name, requestBody)
        }
    }

}
